package org.tony.spider.zhulang;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.tony.spider.book.ChapterInfo;
import org.tony.spider.common.Command;
import org.tony.spider.common.GetRequestor;
import org.tony.spider.common.Rule;
import org.tony.spider.common.cmd.CommandInvoker;
import org.tony.spider.util.SpiderConfigParser;

public class QueryBookDetailRunner
    implements Runnable
{
  private ChapterInfo info;
  private File        file;

  public QueryBookDetailRunner(ChapterInfo info)
  {
    this.info = info;
    file = new File(info.getSavePath());
    if (!file.exists())
    {
      file.getParentFile().mkdirs();
      try
      {
        file.createNewFile();
      }
      catch (IOException e)
      {
        System.err.println(info.getTitle() + ".txt create failed");
      }
    }
  }

  /**
   * zhulang = "div.readpage_leftntxt"
   */
  public void run()
  {
    try
    {
      if (!info.getIsVip())
      {
        GetRequestor gq = new GetRequestor();
        String content = gq.startGet(info.getUrl());
        Document doc = Jsoup.parse(content);
        Elements elements = null;
        Object arg = doc;
        Rule rule = SpiderConfigParser.getInstance().getNovelRule(info.getBook().getFrom().name());
        if (rule != null)
        {
          Iterator<Command> iter = rule.getCommands().iterator();
          while (iter.hasNext())
          {
            elements = (Elements)CommandInvoker.getInstance().invoke(iter.next(), arg);
            arg = elements;
          }
        }
        if (elements.size() == 1)
        {
          Element el = elements.first();
          Iterator<Node> nodes = el.childNodes().iterator();
          OutputStream fos = new FileOutputStream(file);
          while (nodes.hasNext())
          {
            Node node = nodes.next();
            if (node instanceof TextNode)
            {
              fos.write(((TextNode)node).text().getBytes("UTF-8"));
              fos.write("\n".getBytes("UTF-8"));
            }
          }
          fos.flush();
          fos.close();
        }
      }

    }
    catch (Exception e)
    {
      e.printStackTrace();
      System.err.println(e);
    }

  }
}
